//
//  NSObject+Extension.swift
//  SwiftProject
//
//  Created by qindong on 2021/3/10.
//

import Foundation

extension NSObject {
    // MARK: - 交换方法
    public class func swizzleMethod(for aClass: AnyClass, originalSelector: Selector,swizzledSelector: Selector) {
        let originalMethod = class_getInstanceMethod(aClass, originalSelector)
        let swizzledMethod = class_getInstanceMethod(aClass, swizzledSelector)
        let didAddMethod = class_addMethod(aClass, originalSelector, method_getImplementation(swizzledMethod!), method_getTypeEncoding(swizzledMethod!))
        if didAddMethod {
            class_replaceMethod(aClass, swizzledSelector, method_getImplementation(originalMethod!), method_getTypeEncoding(originalMethod!))
        } else {
            method_exchangeImplementations(originalMethod!, swizzledMethod!)
        }
    }
    
    // MARK: - 获取所属class字符串快捷方法
    public func nameOfClass(anyClass : AnyClass) -> String {
        NSStringFromClass(anyClass).components(separatedBy: ".").last!
    }
    
    // MARK: - 获取所有属性
    var getPropertyNameList : [String] {
        //保存属性的个数
        var outCount : UInt32 = 0
        //保存属性名称的数组
        var list : [String] = []
        
        //获取属性集合
        let property = class_copyPropertyList(type(of:self), &outCount)
        //解包
        guard let propertyList = property else {
            return list
        }
        
        for i in 0 ..< Int(outCount){
            //取出单个属性
            let property = propertyList[i]
            let propertyName : UnsafePointer<Int8>? = property_getName(property)
            //获取属性的名字
            guard let char_f = propertyName else{
                continue
            }
            //转换为String
            if let key = NSString(cString: char_f, encoding: String.Encoding.utf8.rawValue) as String? {
                //添加到数组
                list.append(key)
            }
        }
        return list
    }
}


